package com.zjy.service.impl;

import com.zjy.exception.BusinessException;
import com.zjy.pojo.entity.User;
import com.zjy.repository.UserRepository;
import com.zjy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User login(String username, String password) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BusinessException("用户不存在"));

        if (!user.getPassword().equals(password)) {
            throw new BusinessException("密码错误");
        }
        return user;
    }

    @Override
    public User register(User user) {
        userRepository.findByUsername(user.getUsername())
                .ifPresent(existingUser -> {
                    throw new BusinessException("用户名已存在");
                });
        return userRepository.save(user);
    }

    @Override
    public User getProfile(Long userId) {
        return userRepository.findById(userId)
                .orElseThrow(() -> new BusinessException("用户不存在"));
    }

    @Override
    public User updateProfile(Long userId, User user) {
        User existingUser = userRepository.findById(userId)
                .orElseThrow(() -> new BusinessException("用户不存在"));

        existingUser.setRealName(user.getRealName());
        existingUser.setGender(user.getGender());
        existingUser.setHobby(user.getHobby());
        existingUser.setUndergraduate(user.getUndergraduate());
        existingUser.setTarget(user.getTarget());

        return userRepository.save(existingUser);
    }
}